import { useEffect, useState } from "react";
import { apiRoute } from "../../utils/api";
import styles from "./Index.module.css";
import { ListItem } from "../../components/ListItem/ListItem";
import { Component } from "../../domain/Component";
import { Button, message } from "antd";
import { ws } from "../../utils/websocket";

export const Index = () => {
  const [components, setComponents] = useState<Component[]>([]);

  const refresh = () => {
    fetch(apiRoute("getComponentList")).then((res) => {
      res.json().then(({ data }) => {
        setComponents(data);
      });
    });
  };

  useEffect(() => {
    refresh();
  }, []);

  return (
    <div className={styles.box}>
      <ListItem components={components} refreshList={refresh} />

      <div className={styles.buttonBox}>
        <Button
          type="primary"
          onClick={() => {
            ws.sendObj("clearPreview", "null", (data) => {
              message.success(data.data);
            });
          }}
        >
          清空
        </Button>
        <Button
          type="primary"
          onClick={() => {
            ws.sendObj("download", "null", (data) => {
              console.log(data);
              message.success(data.data);
              window.open("/api/download");
            });
          }}
        >
          下载
        </Button>
        <Button
          type="primary"
          onClick={() => {
            window.open("/preview");
          }}
        >
          预览
        </Button>
        <Button
          type="primary"
          onClick={() => {
            window.open("/result");
          }}
        >
          最终效果
        </Button>
      </div>
    </div>
  );
};
